// pages/detail/detail.js
// pages/detail/detail.js
const app = getApp();

Page({
  data: {
    resource: null,
    showToast: false,
    copyText: '',    
    showCopy: false  
  },
  
  collectResource() {
    const resource = this.data.resource;
    let collectedIds = wx.getStorageSync('collectedIds') || [];
    const index = collectedIds.indexOf(resource.id);
    
    if (index === -1) {
      // 收藏资源
      collectedIds.push(resource.id);
      wx.showToast({
        title: '收藏成功',
        icon: 'success'
      });
    } else {
      // 取消收藏
      collectedIds.splice(index, 1);
      wx.showToast({
        title: '取消收藏',
        icon: 'none'
      });
    }
    
    wx.setStorageSync('collectedIds', collectedIds);
    this.setData({
      isCollected: index === -1
    });
  },

  onLoad(options) {
    console.log('detail onLoad');
    const id = parseInt(options.id);
    // 从全局数据中查找对应的资源
    const resource = app.globalData.resources.find(item => item.id === id);
    
    if (resource) {
      this.setData({ resource });
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: resource.title
      });
    } else {
      // 资源不存在时返回上一页
      wx.navigateBack();
      wx.showToast({
        title: '资源不存在',
        icon: 'none'
      });
    }

    // 检查是否已收藏
    const collectedIds = wx.getStorageSync('collectedIds') || [];
    this.setData({
      isCollected: collectedIds.includes(id)
    });

    // 新增：初始化复制文本
    if (resource) {
      //let text = '官网：https:www.maxiaocang.xyz\n\n';
      let text = `${resource.netdiskName || '未知网盘'}-码小仓资源下载\n`;
      text += `链接：${resource.netdiskLink}\n`;
      if (resource.shareCode) {
        text += `提取码：${resource.shareCode}`;
      }
      
      this.setData({ copyText: text });
    }
    
  },
  
  // 新增：显示复制区域
  showCopyArea() {
    this.setData({ showCopy: true });
  },
  
  // 新增：隐藏复制区域
  hideCopyArea() {
    this.setData({ showCopy: false });
  },

  // 复制文本
  copyText(e) {
    const text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: () => {
        // 显示复制成功提示
        this.setData({ showToast: true });
        setTimeout(() => {
          this.setData({ showToast: false });
        }, 2000);
      }
    });
  },
  
  // 复制所有下载信息
  copyAllInfo() {
    const resource = this.data.resource;
    if (!resource) return;
    
    // 拼接所有信息
    let allInfo = `${resource.netdiskName || '未知网盘'}-码小仓：https:www.maxiaocang.xyz\n`;
    allInfo += `链接：${resource.netdiskLink}\n`;
    if (resource.shareCode) {
      allInfo += `提取码：${resource.shareCode}`;
    }
    console.log(allInfo);
  },
  
  // 复制文本到剪贴板
  copyToClipboard(text) {
    // 先检查权限
    wx.getSetting({
      success: (res) => {
        // 查看是否有剪贴板权限
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 没有权限，请求授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              // 授权成功，执行复制
              this.setClipboard(text);
            },
            fail: () => {
              // 授权失败，引导用户手动开启
              wx.showModal({
                title: '权限不足',
                content: '需要获取剪贴板权限才能完成复制操作，请在设置中开启',
                confirmText: '去设置',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    // 打开设置页面
                    wx.openSetting({
                      success: (settingRes) => {
                        if (settingRes.authSetting['scope.writePhotosAlbum']) {
                          this.setClipboard(text);
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          // 已有权限，直接复制
          this.setClipboard(text);
        }
      }
    });
  },

  // 实际执行复制的函数
  setClipboard(text) {
    wx.setClipboardData({
      data: text,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: (err) => {
        console.error('复制失败', err);
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 打开链接
  openLink() {
    if (this.data.resource && this.data.resource.网盘链接) {
      console.log('openLink()');
      wx.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(this.data.resource.网盘链接)}`
      });
    }
  },
  
  // 预览主图
  previewImage() {
    if (this.data.resource && this.data.resource.imageUrl) {
      wx.previewImage({
        urls: [this.data.resource.imageUrl]
      });
    }
  },
  
  // 预览截图
  previewScreenshot(e) {
    const url = e.currentTarget.dataset.url;
    const screenshots = this.data.resource.screenshots;
    if (screenshots && screenshots.length) {
      wx.previewImage({
        urls: screenshots,
        current: url
      });
    }
  },
  
  // 分享功能
  onShareAppMessage() {
    if (this.data.resource) {
      return {
        title: this.data.resource.title,
        path: `/pages/detail/detail?id=${this.data.resource.id}`,
        imageUrl: this.data.resource.imageUrl
      }
    }
  }
})



